<template>
    <view>
        <view v-for="(item,index) in areaName">
            <view class="MDistrict">
                <view class="MDistrict-name">
                    <picker mode="multiSelector" :disabled="readOnly" @change="onChange(index)" @columnchange="onColumnChange"
                            :value="curValue" :range="options" range-key="AREA_NAME_">
                        <div @click="changeDistrict(index)" style="display: flex;align-items: center">
                            <div :class="item[0]?'multiSelector-name':'multiSelector-name-hover'">{{item[0] ? getAddressStr(item) : i18n('getAddressStr','获取地址') }}</div>
                            <my-icon v-if="!readOnly && item[0]" @click.stop="removeSelect(index)" type="icon-icon-test26" style="color: rgba(201, 201, 201, 1)"></my-icon>
                        </div>
                    </picker>
                </view>
                <my-icon v-if="!item[0] || readOnly" style="color: rgba(66, 133, 244, 1)" type="icon-ditu1"></my-icon>
            </view>
            <uv-textarea v-if="showAddress" :disabled="readOnly" v-model="item[3]" style="margin: 0.5rem 0rem;height: 3rem" :maxlength="50"   :placeholder="i18n('address','请输入详情地址')" @change="setAddress(item[3],index)"></uv-textarea>
        </view>
        <button v-if="metadata.options.isMultiple && !readOnly" class="mini-btn" type="primary" size="mini" @click="addArea">添加地区</button>
    </view>
</template>

<script>
/**
 * 地区控件
 */

import MForm from "../js/MForm";
import FormBase from "../js/FormBase";
import {FormApi} from "@/api/FormApi.js";
import Util from '@/js/Util.js'
import MInput from "../MInput/MInput";

export default {
    name: "MDistrict",
    components: {MInput},
    mixins: [MForm, FormBase],
    data() {
        return {
            defOptions: [],//控件区域
            options: [],//渲染弹窗滚动地区数据
            curValue: [],//用于回显 存放的是下标['1','2','3']显示第一个第二个第三个
            area_code:[],//回显存储地区的id
            areaName:[],//回显存储地区的名称
            curAddress: {},  //暂存数据 点击确认返回的数据
            selectedAddress: {},
        }
    },
    computed: {
        //市
        showCity() {
            return this.metadata.options.isCity;
        },
        //县
        showCounty() {
            return this.metadata.options.isCounty;
        },
        //详情
        showAddress() {
            return this.metadata.options.isAddress;
        }
    },
    created() {
        this.initCurAddress();
        this.initValue(this.value);
        if(!this.metadata.options.isMultiple && !this.readOnly && this.areaName.length==0){
            this.addArea()
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        async changeDistrict(index_) {
            this.curValue = [];
            const indexMap = ['provinces'];
            if(this.showCity){
                indexMap.push('cities')
            }
            if(this.showCounty){
                indexMap.push('counties')
            }
            if (this.area_code[index_]) {
                for (let index = 0; index < indexMap.length; index++) {
                    const res = indexMap[index];
                    if (index === 0) {
                        await this.getsProvince(res, {});
                    } else {
                        let param = {};
                        param["PARENT_CODE_"] = this.area_code[index_][index - 1];
                        await this.getsProvince(res, param);
                    }
                }
            }
            indexMap.forEach((res,index)=>{
                let key = this.getCurIndex(this.area_code[index_][index],this.options[index])
                this.curValue.push(key)
            })
            const indexData= ['province'];
            if(this.showCity){
                indexData.push('city')
            }
            if(this.showCounty){
                indexData.push('county')
            }
            for (let i = 0; i< indexData.length; i++) {
                if(this.area_code[index_]){
                    this.curAddress[indexData[i]+'_code'] = this.area_code[index_][i]
                }
                if(this.areaName[index_]){
                    this.curAddress[indexData[i]] = this.areaName[index_][i]
                }
            }
        },
        //获取下标
        getCurIndex(code, ary) {
            let index = "";
            for (let i = 0; i < ary.length; i++) {
                if (code == ary[i].AREA_CODE_) {
                    index = i;
                    break;
                }
            }
            return index;
        },
        /*
        获取地区控件的配置的区域属性
        */
        initCurAddress() {
            this.defOptions= [[{"AREA_NAME_": this.i18n('SelectProvince','选择省'), "AREA_CODE_": "-1"}]]
            this.curAddress = {
                province: "",
                province_code: ""
            };
            if (this.showCity) {
                this.curAddress['city'] = '';
                this.curAddress['city_code'] = '';
                this.defOptions.push([{"AREA_NAME_": this.i18n('SelectCity','选择市'), "AREA_CODE_": "-1"}])
            }
            if (this.showCounty) {
                this.curAddress['county'] = '';
                this.curAddress['county_code'] = '';
                this.defOptions.push([{"AREA_NAME_": this.i18n('SelectCounty','选择县(区)'), "AREA_CODE_": "-1"}])
            }
            this.options = Util.deepClone(this.defOptions);
        },
        /*
        初始化数据
        */
        initValue(val) {
            let self = this;
            if (!val) {
                //没有数据先加载省份数据
                if (!this.readOnly) {
                    this.getsProvince("provinces", {});
                }
                return;
            }
            this.selectedAddress = JSON.parse(val);
            const indexValue = ['province']
            const curKey = ['province_code']
            if(this.showCity){
                indexValue.push('city')
                curKey.push('city_code')
            }
            if(this.showCounty){
                indexValue.push('county')
                curKey.push('county_code')
            }
            if(this.showAddress){
                indexValue.push('address')
            }
            this.curChanger(indexValue,function (data) {
                self.areaName=data
            })
            this.curChanger(curKey,function (data) {
                self.area_code=data
            })
        },
        /*
        拼接数据
        */
        curChanger(indexValue,callback){
            let obj = {};
            let list = []
            indexValue.forEach(res=>{
                if(this.selectedAddress[res]){
                    obj[res]=this.selectedAddress[res].split(',')
                }
            })
            for(let i=0;i<obj[indexValue[0]].length;i++){
                let indexMap = {}
                indexValue.forEach((res,index)=>{
                    indexMap[index] = obj[res]?obj[res][i]:''
                })
                //获取地区名称
                list.push(indexMap)
            }
            if(callback){
                callback(list)
            }
        },
        getAddressStr(item){
            if(item){
                let list = Object.values(item);
                if(list.length==4){
                    list.splice(3,1)
                }
                return list.join('-')
            }
            return '';
        },
        /**
         * 获取地址选项
         * @param key
         * @param config
         * @param callback
         * @returns {Promise<void>}
         */
        async getsProvince(key, config) {
            await FormApi.queryAddress(key, config).then(res => {
                if (!res?.success) return;
                const indexMap = { provinces: 0, cities: 1, counties: 2 };
                this.options[indexMap[key]] = Util.deepClone([
                    ...(this.defOptions[indexMap[key]] || []),
                    ...(res.data || [])
                ]);
            })
        },
        //滚动地区
        onColumnChange(e) {
            //获取当前选择的选项数据
            let option = this.options[e.detail.column][e.detail.value];
            //查询地址的key
            let key = "";
            //当前地址code
            let code = option.AREA_CODE_?option.AREA_CODE_:'';
            //当前地址name
            let name = option.AREA_NAME_?option.AREA_NAME_:'';
            //是否需要查询接口
            let flag = true;
            //选择空选项时
            if (code == "-1") {
                flag = false;
                code = "";
                name = "";
            }
            switch (e.detail.column) {
                case 0:
                    key = "cities";
                    this.provinceChange(code, name);
                    break
                case 1:
                    key = "counties";
                    this.cityChange(code, name);
                    break;
                case 2:
                    this.countyChange(code, name);
                    flag = false;
                    break;
            }
            //判断需要查询接口
            if (!flag) {
                this.$forceUpdate();
                return;
            }
            //获取下一级地址选项
            if (this.showCity &&  key == "cities"){
                this.getsProvince(key, {"PARENT_CODE_": code});
            }
            if (this.showCounty &&  key == "counties"){
                this.getsProvince(key, {"PARENT_CODE_": code});
            }

        },
        //滚动市
        provinceChange(code, name) {
            // 更新当前省份信息
            this.curAddress = {
                ...this.curAddress,
                province: name,
                province_code: code
            };
            // 获取并设置当前省份索引
            const provinceIndex = this.getCurIndex(code, this.options[0]);
            this.curValue[0] = provinceIndex;
            // 重置下级选择（城市和区县）
            if (this.curValue.length > 1) {
                this.curValue[1] = 0;  // 重置城市选择
                if (this.curValue.length > 2) {
                    this.curValue[2] = 0; // 重置区县选择
                }
            }
        },
        //滚动县
        cityChange(code, name) {
            this.curAddress.city = name;
            this.curAddress.city_code = code;
            if(this.curValue[2]){
                this.curValue[2] = 0
            }
        },
        //滚动区
        countyChange(code, name) {
            this.curAddress.county = name;
            this.curAddress.county_code = code;
        },
        //点击确定
        onChange(index) {
            this.selectedAddress = this.mergeAddressData(this.selectedAddress, this.curAddress, index)
            let value = JSON.stringify(this.selectedAddress);
            this.setData(value);
        },
        // 处理地址数据合并
        mergeAddressData(selected, current, index) {
            const result = {...selected};
            Object.keys(current).forEach(key => {
                // 分割原始数据为数组
                const originalValues = selected[key] ? selected[key].split(',') : [];
                // 如果index存在则替换，不存在则追加
                if (index < originalValues.length) {
                    originalValues[index] = current[key];
                } else {
                    originalValues.push(current[key]);
                }
                // 重新组合为字符串
                result[key] = originalValues.join(',');
            });
            return result;
        },
        //修改详情
        setAddress(name,index){
            if(!this.selectedAddress.address){
                this.selectedAddress['address'] = ''
            }
            this.selectedAddress.address = this.updateAddress(this.selectedAddress.address, name, index);
            let value = JSON.stringify(this.selectedAddress);
            this.setData(value);
        },
        updateAddress(original, newValue, index) {
            const arr = original.split(',');
            index < arr.length ? arr[index] = newValue : arr.push(newValue);
            return arr.join(',');
        },
        removeSelect(index){
            if(this.areaName.length==1){
                this.curValue=[];
                this.area_code=[];
                this.areaName=[];
                this.setData('')
                if(!this.metadata.options.isMultiple){
                    this.addArea()
                };
                this.$forceUpdate()
            }else {
                const cleanEmptyFields = true; // 是否清理空字段
                Object.keys(this.selectedAddress).forEach(key => {
                    if (this.selectedAddress[key]) {
                        const values = this.selectedAddress[key].toString().split(',');
                        if (index >= 0 && index < values.length) {
                            values.splice(index, 1);
                            this.selectedAddress[key] = values.length > 0 ? values.join(',') : undefined;

                            if (cleanEmptyFields && !this.selectedAddress[key]) {
                                delete this.selectedAddress[key];
                            }
                        }
                    }
                });
                let value = JSON.stringify(this.selectedAddress);
                this.setData(value);
                this.initValue(this.value);
            }
        },
        /*
        添加地区
         */
        addArea(){
            if(this.areaName.length>0 && !this.areaName[this.areaName.length-1][0]){
                uni.showToast({
                    title: '请填充好上一个地址',
                    duration: 2000,
                    icon: 'none'
                });
                return
            }
            let item = {}
            this.defOptions.forEach((res,index)=>{
                item[index]=""
            })
            this.areaName.push(item)
            this.area_code.push(item)
        },
    },
    watch: {
        value(val) {
            this.initValue(val);
        }
    },
}
</script>

<style scoped>
.MDistrict {
    border-radius: 0.17rem;
    border: 1px solid rgba(232, 232, 232, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding:0.5rem;
    margin-bottom: 0.5rem;
}

.MDistrict-name {
    flex: 1;
    color: rgba(0, 0, 0, 0.85);
}

.multiSelector-name-hover {
    color:#ccc;
    flex: 1;
    margin-right: 0.5rem;
}

.multiSelector-name {
    color: rgba(0, 0, 0, 0.85);
    flex: 1;
    margin-right: 0.5rem;
}
.mini-btn{
    width: 100%;
}
</style>
